
package com.hlkj.pay.app.ad.impl;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.ad.IAdAppService;
import com.hlkj.pay.app.ad.IAdPayOrderCallService;
import com.hlkj.pay.common.AdResultCode;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.dto.ad.AdPayTypDto;
import com.hlkj.pay.enums.AdEnum;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.infrastructure.model.ad.AdInfoConfigDO;
import com.hlkj.pay.infrastructure.model.ad.AdInfoDO;
import com.hlkj.pay.infrastructure.model.common.PlatFormConfigDO;
import com.hlkj.pay.service.ad.IAdInfoService;
import com.hlkj.pay.service.common.IPlatFormConfigService;
import com.hlkj.pay.vo.ad.req.AdInfoConfigReq;
import com.hlkj.pay.vo.ad.req.AdInfoReq;
import com.hlkj.pay.vo.ad.req.UpdateStatusReq;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.StringPool;

/**
 * @author HlpayTeam
 * @date 2024/10/22 18:25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdAppServiceImpl implements IAdAppService {

    private final IAdInfoService adInfoService;

    private final IPlatFormConfigService platFormConfigService;

    private final IAdPayOrderCallService adPayOrderCallService;

    @Override
    public CommonResult<Void> saveAd(AdInfoReq adInfoReq) {
        log.info("saveAd adInfoReq:{}", JsonUtils.toJsonString(adInfoReq));
        try {
            AdInfoDO adInfoDO = BeanUtil.copyProperties(adInfoReq, AdInfoDO.class);
            adInfoService.saveAd(adInfoDO);
            adInfoReq.setId(adInfoDO.getId());
            AdInfoDO udpateAdInfoDO = new AdInfoDO();
            udpateAdInfoDO.setUrl(url(adInfoReq));
            udpateAdInfoDO.setId(adInfoDO.getId());
            adInfoService.updateAd(udpateAdInfoDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("saveAd error:{}", e.getMessage(),e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> updateAd(AdInfoReq adInfoReq) {
        log.info("updateAd adInfoReq:{}", JsonUtils.toJsonString(adInfoReq));
        try {
            AdInfoDO adInfoDO = adInfoService.queryById(adInfoReq.getId());
            if (adInfoDO == null) {
                return CommonResult.error(AdResultCode.AD_NOT_EXITS);
            }
            adInfoReq.setUrl(url(adInfoReq));
            AdInfoDO udpateAdInfoDO = BeanUtil.copyProperties(adInfoReq, AdInfoDO.class);
            udpateAdInfoDO.setId(adInfoDO.getId());
            adInfoService.updateAd(udpateAdInfoDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("updateAd error:{}", e.getMessage(),e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> delAd(Long id) {
        log.info("delAd id:{}", id);
        try {
            AdInfoDO adInfoDO = adInfoService.queryById(id);
            if (adInfoDO == null) {
                return CommonResult.error(AdResultCode.AD_NOT_EXITS);
            }
            adInfoService.delAd(id);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("delAd error:{}", e.getMessage(),e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> updateAdStatus(UpdateStatusReq updateStatusReq) {
        log.info("updateAdStatus updateStatusReq:{}", JsonUtils.toJsonString(updateStatusReq));
        try {
            AdInfoDO adInfoDO = adInfoService.queryById(updateStatusReq.getId());
            if (adInfoDO == null) {
                return CommonResult.error(AdResultCode.AD_NOT_EXITS);
            }
            adInfoService.updateAdStatus(updateStatusReq.getId(), updateStatusReq.getStatus());
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("updateAdStatus error:{}", e.getMessage(),e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> updateAdConfig(AdInfoConfigReq adInfoConfigReq) {
        log.info("updateAdConfig adInfoConfigReq:{}", JsonUtils.toJsonString(adInfoConfigReq));
        try {
            AdInfoConfigDO infoConfigDO = BeanUtil.copyProperties(adInfoConfigReq, AdInfoConfigDO.class);
            if (!CollectionUtils.isEmpty(adInfoConfigReq.getPayTypeList())) {
                List<PlatFormConfigDO> platFormConfigList = platFormConfigService.platFormConfigList(CommonEnum.CONFIG_TYPE.AD_PAY_TYPE.getType());
                if (!CollectionUtils.isEmpty(platFormConfigList)) {
                    PlatFormConfigDO platFormConfigDO = platFormConfigList.get(0);
                    String configValue = platFormConfigDO.getConfigValue();
                    List<AdPayTypDto> payTypes = JsonUtils.parseArray(configValue, AdPayTypDto.class);
                    List<AdPayTypDto> collect = payTypes.stream().filter(payType -> adInfoConfigReq.getPayTypeList().contains(payType.getWayCode())).collect(Collectors.toList());
                    adInfoConfigReq.setPayTypes(collect);
                }
            }
            infoConfigDO.setPayTypeJson(JsonUtils.toJsonString(adInfoConfigReq.getPayTypes()));
            AdInfoConfigDO adInfoConfigDO = adInfoService.queryConfigByAdId(adInfoConfigReq.getAdId());
            if (adInfoConfigDO == null) {
                adInfoService.saveConfig(infoConfigDO);
            }
            else {
                infoConfigDO.setId(adInfoConfigDO.getId());
                adInfoService.updateConfig(infoConfigDO);
                // 回传扣率 有变更 订单数量以及历史回传数据从新计算
                if (adInfoConfigDO.getCallRate().compareTo(adInfoConfigReq.getCallRate()) != 0) {
                    adPayOrderCallService.resetCallRate(adInfoConfigDO.getAdId());
                }
            }
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("updateAdConfig error:{}", e.getMessage(),e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    String url(AdInfoReq adInfoReq) {
        if (adInfoReq.getUrl().contains("?id=")) {
            return adInfoReq.getUrl();
        }
        AdEnum.AD_TYPE adType = AdEnum.AD_TYPE.from(adInfoReq.getType());
        // https://h5.qywh8.com/phone-bill?id=44&type=1
        StringBuilder sb = new StringBuilder(adInfoReq.getUrl());
        if (!adInfoReq.getUrl().equals(StringPool.SLASH)) {
            sb.append(StringPool.SLASH);
        }
        sb.append(adType.getPrefix());
        sb.append(StringPool.QUESTION_MARK);
        sb.append("id=");
        sb.append(adInfoReq.getId());
        sb.append(StringPool.AMPERSAND);
        sb.append("type=");
        sb.append(adType.getCode());
        return sb.toString();
    }

}
